//
// Created by sgyt on 2020/3/21.
//
#include <stdlib.h>
#include <stdio.h>
#include <sys/shm.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include "shmdata.h"

int main(int argc,char *argv[])
{
    int shmId,res;
    //数据共享区
    struct shared_use_st *data;
    //分配的共享内存的原始首地址
    void *shm = NULL;

    //创建一个共享存储区
    shmId = shmget((key_t)1234, sizeof(struct shared_use_st),IPC_CREAT|0666);
    if(shmId == -1)
    {
        perror("shmget is error\n");
        exit(EXIT_FAILURE);
    }

    //将一个共享存储区绑定到一段空间上
    shm = shmat(shmId,0,0);
    if(shm == (void *)-1)
    {
        perror("shmat is error\n");
        exit(EXIT_FAILURE);
    }

    //设置共享内存
    printf("Memory attached at %X\n", (int)shm);

    data = (struct shared_use_st *)shm;

    //第一次读的时候设置为0
    data->write = 0;
    while(1)
    {
        if(data->write != 0)
        {
            printf("Your wirte:%s\n",data->text);
            data->write = 0;
            if(strncmp(data->text,"end",3)==0)
            {
                break;
            }
        }
        sleep(1);
    }

    //将内存共享区和内存断开
    res = shmdt(shm);
    if(res == -1)
    {
        perror("shmdt is error\n");
        exit(EXIT_FAILURE);
    }

    //删除内存共享
    res = shmctl(shmId,IPC_RMID,0);
    if(res == -1)
    {
        perror("shmctl is error\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}
